package com.boot2.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class ResourceUtil {

    public static void main(String args[]) {
        System.out.println(getResourceFile("/WEB-INF/resources/abc.txt").toString());
    }

    public static File getResourceFile(String resourceName) {
        String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
//        String path = ResourceUtil.class.getResource("/").getFile();
        // System.out.println("path: " + path);
//        String root = "";
//        if (path.lastIndexOf("/WEB-INF/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/WEB-INF/"));
//        }
//        else if (path.lastIndexOf("/target/classes/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/target/classes/"));
//        }
//        else if (path.lastIndexOf("/target/test-classes/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/target/test-classes/"));
//        }
//        else if (path.lastIndexOf("/build/classes/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/build/classes/"));
//        }
//        else if (path.lastIndexOf("/bin/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/bin/"));
//        }
        return new File(path + resourceName);
    }

    public static InputStream getInputStream(String resourceName) {
        Resource resource = new ClassPathResource(resourceName);
        try {
            return resource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            log.error(resourceName+",读取异常",e);
        }
        return null;
    }

    /**
     * @param resourceName
     * @return
     * @author nixianjun 2013.8.9
     */
    public static String getResourceFileName(String resourceName) {
//        String path = ResourceUtil.class.getResource("/").getFile();
//        String path = ResourceUtil.class.getResource("/").getFile();
        String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
//        String root = null;
//        if (path.lastIndexOf("/WEB-INF/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/WEB-INF/"));
//        }
//        else if (path.lastIndexOf("/target/classes/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/target/classes/"));
//        }
//        else if (path.lastIndexOf("/build/classes/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/build/classes/"));
//        }
//        else if (path.lastIndexOf("/bin/") > 0)
//        {
//            root = path.substring(0, path.lastIndexOf("/bin/"));
//        }
        return path + resourceName;
    }
}
